import requests
import json

def list_ollama_models():
    print("=== 列出Ollama可用模型 ===")
    
    # Ollama列出模型的API
    url = "http://localhost:11434/api/tags"
    
    try:
        print(f"正在请求Ollama服务: {url}")
        response = requests.get(url, timeout=10)
        
        if response.status_code == 200:
            data = response.json()
            print(f"成功获取模型列表！响应状态码: {response.status_code}")
            print(f"完整响应: {json.dumps(data, ensure_ascii=False, indent=2)}")
            
            if 'models' in data and data['models']:
                print("\n可用模型列表:")
                for model in data['models']:
                    print(f"- 模型名称: {model.get('name')}")
                    print(f"  模型ID: {model.get('model')}")
                    print(f"  大小: {model.get('size')}")
                    print(f"  上次修改: {model.get('modified_at')}")
                    print()
                return data['models']
            else:
                print("Ollama服务中没有找到任何模型。")
                print("请先使用 'ollama pull <model_name>' 命令下载模型。")
        else:
            print(f"请求失败！状态码: {response.status_code}")
            print(f"响应内容: {response.text}")
    except requests.exceptions.ConnectionError:
        print("无法连接到Ollama服务。")
        print("请确保Ollama服务正在运行。")
    except Exception as e:
        print(f"发生错误: {str(e)}")
    
    return []

if __name__ == "__main__":
    list_ollama_models()